import 'package:flutter/material.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerStudent.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/sidebars/studentSidebar.dart';
import 'package:just_audio/just_audio.dart';
import '../../themes/appTheme.dart';

class StudentAudioBooksPage extends StatefulWidget {
  const StudentAudioBooksPage({Key? key}) : super(key: key);
  @override
  _StudentAudioBooksPageState createState() => _StudentAudioBooksPageState();
}

class _StudentAudioBooksPageState extends State<StudentAudioBooksPage> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Future<void> dispose() async {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build AudioBooksPage');
    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.studentPageItems
        .indexWhere((page) => page.route == Get.currentRoute);
    final PageStyles _pageStyles = PageStyles();

    return Scaffold(
      appBar: isSmallScreen ? CustomAppBar(title: 'Audio Books'.tr) : null,
      drawer: isSmallScreen ? StudentAppDrawer() : null,
      body: Container(
        decoration: _pageStyles.pageBoxDecoration(),
        child: Container(
          //margin: EdgeInsets.only(left: 9.0),
          child: Row(
            children: [
              Visibility(
                  visible: !isSmallScreen,
                  child: Container(
                      child: StudentSidebarX(
                          selectedIndex: _selectedSidebarItem,
                          isBigScreen: isBigScreen))),
              Expanded(
                child: Container(
                  margin: _pageStyles.mainContainerPageEdgeInsets(),
                  child: Column(
                    children: [
                      Playlist(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ignore: must_be_immutable
class Playlist extends StatefulWidget {
  Playlist({Key? key}) : super(key: key);

  @override
  State<Playlist> createState() => _PlaylistState();
}

class _PlaylistState extends State<Playlist> {
  final BooksController _booksController = Get.find();
  final AudioPlayer player = AudioPlayer();
  int _currentSelectedIndex = -1;

  @override
  void initState() {
    _booksController.fetchAudioPlayBooksItems();
    super.initState();
  }

  @override
  Future<void> dispose() async {
    super.dispose();
    _booksController.audioPlayBookItems.clear();
    await player.stop();
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (_booksController.audioPlayBookItems.isNotEmpty) {
        return Expanded(
            child: ListView.builder(
          itemCount: _booksController.audioPlayBookItems.length,
          itemBuilder: (context, index) {
            return Container(
              margin: EdgeInsets.symmetric(vertical: 3.0),
              decoration: BoxDecoration(
                color: _currentSelectedIndex == index
                    ? Get.isDarkMode
                        ? AppTheme.colors.primaryLight
                        : AppTheme.colors.orangeBtn
                    : Get.isDarkMode
                        ? AppTheme.colors.darkTheme2
                        : Colors.white.withOpacity(0.3),
                borderRadius: BorderRadius.circular(3),
              ),
              child: ListTile(
                contentPadding: EdgeInsets.all(9.0),
                leading: Icon(
                  Icons.music_note,
                  color: _currentSelectedIndex == index
                      ? Get.isDarkMode
                          ? Colors.black
                          : Colors.white
                      : Get.isDarkMode
                          ? Get.theme.primaryColorDark
                          : Get.theme.primaryColorDark.withOpacity(0.8),
                ),
                title: Text(
                  '${_booksController.audioPlayBookItems[index].bookTitle}',
                  style: _currentSelectedIndex == index
                      ? TextStyle(
                          fontSize: 16.0,
                          color: Get.isDarkMode ? Colors.black : Colors.white,
                        )
                      : TextStyle(
                          fontSize: 16.0,
                          color: Get.isDarkMode ? Colors.white : Colors.black,
                        ),
                ),
                trailing: Wrap(
                  spacing: 12,
                  children: [
                    Container(
                      padding: EdgeInsets.all(6.0),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: _currentSelectedIndex == index
                            ? Get.isDarkMode
                                ? Colors.black
                                : Colors.white.withOpacity(0.3)
                            : Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Colors.white.withOpacity(0.3),
                      ),
                      child: MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: GestureDetector(
                            child: Icon(Icons.play_arrow,
                                size: 24.0,
                                color: _currentSelectedIndex == index
                                    ? Colors.white
                                    : Get.isDarkMode
                                        ? Colors.white
                                        : AppTheme.colors.addBtn),
                            onTap: () async {
                              String? audioasset = _booksController
                                  .audioPlayBookItems[index].audio;

                              await player.setUrl(audioasset!);
                              await player.setAudioSource(AudioSource.uri(
                                  Uri.parse(audioasset),
                                  tag: 'recording'));
                              player.play();
                              setState(() {
                                _currentSelectedIndex = index;
                              });
                            },
                          )),
                    ),
                    Container(
                      padding: EdgeInsets.all(6.0),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: _currentSelectedIndex == index
                            ? Get.isDarkMode
                                ? Colors.black
                                : Colors.white.withOpacity(0.3)
                            : Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Colors.white.withOpacity(0.3),
                      ),
                      child: MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: GestureDetector(
                            child: Icon(
                              Icons.stop,
                              size: 24.0,
                              color: _currentSelectedIndex == index
                                  ? Colors.white
                                  : Get.isDarkMode
                                      ? Colors.white
                                      : AppTheme.colors.pinkBtn,
                            ),
                            onTap: () async {
                              if (_currentSelectedIndex == index) {
                                player.stop();
                                setState(() {
                                  _currentSelectedIndex = -1;
                                });
                              }
                              // if (result == 1) {
                              //   //stop success
                              //   Log.debug(
                              //       "Sound playing stopped successfully.");
                              // } else {
                              //   Log.debug("Error on while stopping sound.");
                              // }
                            },
                          )),
                    ),
                    Container(
                      padding: EdgeInsets.all(6.0),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: _currentSelectedIndex == index
                            ? Get.isDarkMode
                                ? Colors.black
                                : Colors.white.withOpacity(0.3)
                            : Get.isDarkMode
                                ? Get.theme.primaryColor
                                : Colors.white.withOpacity(0.3),
                      ),
                      child: MouseRegion(
                          cursor: SystemMouseCursors.click,
                          child: GestureDetector(
                            child: Icon(
                              Icons.delete_forever_rounded,
                              size: 24.0,
                              color: _currentSelectedIndex == index
                                  ? Colors.white
                                  : Get.isDarkMode
                                      ? Colors.white
                                      : AppTheme.colors.disableBtn,
                            ),
                            onTap: () {
                              String? id = _booksController
                                  .audioPlayBookItems[index].bookId;
                              if (id != null) {
                                player.stop();
                                _booksController
                                    .deleteBooksFromAudioPlaylist(id)
                                    .then((statusResult) {
                                  if (statusResult.status == 1000) {
                                    _currentSelectedIndex = -1;
                                  }
                                  showSnackMsg(statusResult.message.toString());
                                });
                              }
                            },
                          )),
                    ),
                  ],
                ),
              ),
            );
          },
        ));
      } else {
        return Text('');
      }
    });
  }
}
